from decimal import Decimal
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse, Http404, HttpResponseServerError
from django.shortcuts import get_object_or_404
from django.utils import simplejson
from rangevoting.models import Vote, VOTE_RANGE

def vote_on_object(request, app_label, model_name, object_id):
    """
    Store a vote for a given object
    """

    score = request.REQUEST.get('score')

    if not score:
        return HttpResponseServerError("Please include a score!")

    if not request.user.is_authenticated():
        return HttpResponseServerError("Only authenticated users can vote!")

    if (score < VOTE_RANGE[0]) or (score > VOTE_RANGE[1]):
        raise Exception("Score outside of acceptable voting range")

    ctype = get_object_or_404(ContentType, 
                              app_label=app_label,
                              model=model_name)

    model = ctype.model_class()
    obj = get_object_or_404(model, pk=object_id)

    vote = Vote.objects.cast_vote(obj, user, score)

    response = {
        'success': True,
        'score': int(score)
        }

    return HttpResponse(simplejson.dumps(response), 
                        mimetype="text/javascript")
